# 生产环境热修复脚本（适用于紧急bug修复）
param(
    [Parameter(Mandatory=$true)]
    [string]$FixDescription,
    [string]$TargetFile = "",
    [switch]$RestartService = $false
)

$ErrorActionPreference = "Stop"
$venvPath = "C:\VISION_HEALTH\.venv"
$projectPath = "C:\VISION_HEALTH"

function Write-StatusMessage {
    param($Message, $Color = "Cyan")
    Write-Host "[$(Get-Date -Format 'HH:mm:ss')] $Message" -ForegroundColor $Color
}

function Test-ServiceHealth {
    try {
        $response = Invoke-WebRequest -Uri "http://localhost:5000/health" -Method Get -TimeoutSec 5
        return $response.StatusCode -eq 200
    } catch {
        return $false
    }
}

try {
    Write-StatusMessage "=== 生产环境热修复开始 ===" "Green"
    Write-StatusMessage "修复说明: $FixDescription"
    
    # 1. 环境检查
    Set-Location $projectPath
    Write-StatusMessage "当前目录: $(Get-Location)"
    
    # 2. 记录当前状态
    $currentCommit = git rev-parse --short HEAD
    $currentBranch = git branch --show-current
    Write-StatusMessage "当前分支: $currentBranch"
    Write-StatusMessage "当前提交: $currentCommit"
    
    # 3. 服务健康检查
    $serviceOk = Test-ServiceHealth
    Write-StatusMessage "当前服务状态: $(if($serviceOk){'正常'}else{'异常'})"
    
    # 4. 创建热修复分支
    $hotfixBranch = "hotfix-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
    git checkout -b $hotfixBranch
    Write-StatusMessage "已创建热修复分支: $hotfixBranch"
    
    # 5. 拉取最新代码（谨慎操作）
    Write-StatusMessage "检查远程更新..."
    git fetch origin
    $behind = git rev-list --count "HEAD..origin/${currentBranch}"
    
    if ($behind -gt 0) {
        Write-StatusMessage "警告：远程有 $behind 个新提交，是否合并？(y/N)"
        $merge = Read-Host
        if ($merge -eq "y") {
            git merge "origin/${currentBranch}"
            Write-StatusMessage "已合并远程更新"
        }
    }
    
    # 6. 等待用户进行修复
    Write-StatusMessage "请进行代码修复..." "Yellow"
    if ($TargetFile) {
        Write-StatusMessage "建议编辑文件: $TargetFile" "Yellow"
    }
    Write-StatusMessage "完成修复后按任意键继续..."
    Read-Host
    
    # 7. 检查修改
    $changes = git status --porcelain
    if (-not $changes) {
        Write-StatusMessage "未检测到代码修改，退出热修复"
        git checkout $currentBranch
        git branch -D $hotfixBranch
        exit 0
    }
    
    Write-StatusMessage "检测到以下修改:"
    git status --short
    
    # 8. 提交修改
    $commitMessage = "hotfix: $FixDescription"
    git add .
    git commit -m $commitMessage
    Write-StatusMessage "已提交修改: $commitMessage"
    
    # 9. 激活虚拟环境
    Write-StatusMessage "激活虚拟环境..."
    & "$venvPath\Scripts\Activate.ps1"
    
    # 10. 重启服务（如果需要）
    if ($RestartService) {
        Write-StatusMessage "重启服务中..."
        
        # 优雅重启
        Get-Process -Name "python" -ErrorAction SilentlyContinue | 
            Where-Object {$_.CommandLine -like "*waitress*" -or $_.CommandLine -like "*app.py*"} | 
            Stop-Process -Force
        
        Start-Sleep -Seconds 3
        Start-Process -FilePath "powershell.exe" -ArgumentList "-File", ".\run_production_en.ps1" -WindowStyle Minimized
        Start-Sleep -Seconds 10
        
        # 验证服务
        if (Test-ServiceHealth) {
            Write-StatusMessage "✅ 服务重启成功" "Green"
        } else {
            throw "服务重启失败"
        }
    } else {
        Write-StatusMessage "跳过服务重启（配置文件修改可能需要重启）"
    }
    
    # 11. 合并回主分支
    Write-StatusMessage "是否合并修复到主分支？(y/N)"
    $mergeBack = Read-Host
    
    if ($mergeBack -eq "y") {
        git checkout $currentBranch
        git merge $hotfixBranch
        Write-StatusMessage "已合并热修复到主分支"
        
        # 推送到远程（可选）
        Write-StatusMessage "是否推送到远程仓库？(y/N)"
        $pushRemote = Read-Host
        if ($pushRemote -eq "y") {
            git push origin $currentBranch
            Write-StatusMessage "已推送到远程仓库"
        }
        
        # 清理热修复分支
        git branch -d $hotfixBranch
        Write-StatusMessage "已清理热修复分支"
    } else {
        Write-StatusMessage "保留热修复分支: $hotfixBranch"
    }
    
    Write-StatusMessage "=== 热修复完成 ===" "Green"
    Write-StatusMessage "修复内容: $FixDescription" "Green"
    Write-StatusMessage "当前状态: $(if(Test-ServiceHealth){'服务正常'}else{'服务异常'})" "Green"
    
} catch {
    Write-StatusMessage "=== 热修复失败 ===" "Red"
    Write-StatusMessage "错误: $($_.Exception.Message)" "Red"
    
    # 尝试回滚
    try {
        git checkout $currentBranch
        git branch -D $hotfixBranch -ErrorAction SilentlyContinue
        Write-StatusMessage "已回滚到原始状态" "Yellow"
    } catch {
        Write-StatusMessage "回滚失败，请手动检查" "Red"
    }
    
    exit 1
}
